;(function() {

	require(['jquery', 'angular', __uri('./responsive.js'), 'jbox'], function($, angular) {

		var app = angular.module('app', []), group;

		app.factory('safeApply', ['$rootScope', function($rootScope) {//apply
		    return function(scope, fn) {
		        var phase = scope.$root.$$phase;
		        if (phase == '$apply' || phase == '$digest') {
		            if (fn && ( typeof (fn) === 'function')) fn();
		        } else {
		            scope.$apply(fn);
		        }
		    }
		}])
		app.controller('cart', ['$scope', '$http', 'safeApply', function($scope, $http, safeApply) {

			$scope.cbox = false;
			$scope.listArr = [];
			$scope.totalNum = 0;
			$scope.totalPrice = 0;
			$scope.allSize = [];

			var bool = false;

			$scope.cboxAct = function() {
				bool = false;
				for(var i=0;i<$scope.listArr.length;i++) {
					
					if(!$scope.listArr[i].cbox) {
						bool = true;
						break;
					}
				}

				if(bool)
					$scope.cbox = false;
				else
					$scope.cbox = true;
			}

			$scope.boxClick = function() {

				$scope.cbox = !$scope.cbox;
				if($scope.cbox)
					for(var i=0;i<$scope.listArr.length;i++) {
						$scope.listArr[i].boxClick(true);
					}
				else
					for(var i=0;i<$scope.listArr.length;i++) {
						$scope.listArr[i].boxClick(false);
					}
			}

			$scope.allCount = function() {//计算总价总数量

				var num = 0, sum = 0;

				for(var i=0;i<$scope.allSize.length;i++) {
					if($scope.allSize[i].cbox == true) {
						num += parseInt($scope.allSize[i].num);
						sum += $scope.allSize[i].price * $scope.allSize[i].num;
					}
				}

				$scope.totalPrice = sum;
				$scope.totalNum = num;
			}

			$scope.del = function() {

				if($scope.totalNum == 0)
					new jBox('Notice', {
					    autoClose: 500,
						addClass: 'font-b',
						content: '请选中后删除',
						position: {
							x: 'center',
							y: 50
						}
					});
				else {

					new jBox('Confirm', {
						confirmButton: '确定',
						cancelButton: '取消',
						content: '确定删除选中规格?',
						confirm: function() {

							var _items = [];

							for(var i=0;i<$scope.listArr.length;i++) {
								if($scope.listArr[i].cbox == true)
									_items.push({
										'id': $scope.listArr[i].shoid,
										'oper': 'delete'
									});
								else {
									var json = {
										'id': $scope.listArr[i].shoid,
										'items': []
									}
									for(var a=0;a<$scope.listArr[i].allSize.length;a++) {
										if($scope.listArr[i].allSize[a].cbox == true)
											json.items.push({
												'itemid': $scope.listArr[i].allSize[a].itemid,
											    'oper': 'delete'
											});
									}
									_items.push(json);	
								}
									
							}
							$http({
								method: 'POST',
								url: '/control/command',
								params: {
									'command': 'com.jackrain.ds.CommESShopCartSave',
									'getjson': true,
									'JSON': JSON.stringify(_items)
								}
							}).then(function(res) {

								if(res.data.code == 0 && res.data.message == '操作完成') {

									new jBox('Notice', {
									    autoClose: 500,
										addClass: 'font-b',
										content: '删除成功',
										position: {
											x: 'center',
											y: 50
										},
										onClose: function() {
											window.location.reload();
										}
									});
								} else
									new jBox('Notice', {
									    autoClose: 500,
										addClass: 'font-b',
										content: '删除失败,请稍候重试',
										position: {
											x: 'center',
											y: 50
										}
									});
									
							});
						}
					}).open();
				}
			}

			$scope.goPay = function() {

				if($scope.totalNum == 0) {
					new jBox('Notice', {
					    autoClose: 500,
						addClass: 'font-b',
						content: '请选中需要购买的货品',
						position: {
							x: 'center',
							y: 50
						}
					});
				} else {

					var _items = [];

					for(var i=0;i<$scope.listArr.length;i++) {
						var json = {
							'id': $scope.listArr[i].shoid,
							'items': [],
							'ad_client': $scope.listArr[i].id
						}

						$scope.listArr[i].cbox == true ? json['oper'] = 'delete' : '';

						for(var a=0;a<$scope.listArr[i].allSize.length;a++) {
							if($scope.listArr[i].allSize[a].cbox == true)
								json.items.push({
									'itemid': $scope.listArr[i].allSize[a].itemid,
								    'oper': 'delete',
								    'qty': $scope.listArr[i].allSize[a].num,
							      	'specvalue': $scope.listArr[i].allSize[a].sv,
							      	'spec1': $scope.listArr[i].allSize[a].sv.split('|')[0],
							      	'spec2': $scope.listArr[i].allSize[a].sv.split('|')[1],
							      	'goodsid': $scope.listArr[i].allSize[a].$parent.id,
							      	'price': $scope.listArr[i].allSize[a].price
								});
						}
						_items.push(json);	
					}
					$http({
						method: 'POST',
						url: '/control/command',
						params: {
							'command': 'com.jackrain.ds.CommESOrderSave',
							'getjson': true,
							'JSON': JSON.stringify(_items)
						}
					}).then(function(res) {

					});
				}
			}
		}])
		.directive('list', function() {

			return {
				restrict: 'A',
				scope: true,
				controller: ['$scope', '$element', '$attrs',  function($scope, $el, $attrs) {
					$scope.cbox = false;
					$scope.id = $attrs.init;
					$scope.shoid = $attrs.shoid;

					$scope.goodsArr = [];
					$scope.allSize = [];

					$scope.$parent.listArr.push($scope);

					var bool = false;

					$scope.cboxAct = function() {

						bool = false;
						for(var i=0;i<$scope.goodsArr.length;i++) {
							
							if(!$scope.goodsArr[i].cbox) {
								bool = true;
								break;
							}
						}

						if(bool)
							$scope.cbox = false;
						else
							$scope.cbox = true;
					}

					$scope.boxClick = function(opt) {

						$scope.cbox = opt != undefined ? opt : !$scope.cbox;
						if($scope.cbox)
							for(var i=0;i<$scope.goodsArr.length;i++) {
								$scope.goodsArr[i].boxClick(true);
							}
						else
							for(var i=0;i<$scope.goodsArr.length;i++) {
								$scope.goodsArr[i].boxClick(false);
							}
					}

					$scope.$watch('cbox', function(val) {

						if(val)
							$scope.$parent.cboxAct();
						else
							$scope.$parent.cbox = false;

						$scope.$parent.allCount();
					});
				}]
			}
		})
		.directive('goods', ['$http', function($http) {

			return {
				restrict: 'A',
				scope: true,
				controller: ['$scope', '$element', '$attrs', function($scope, $el, $attrs) {
					$scope.cbox = false;
					$scope.ismix = 'Y';//是否混批默认是
					$scope.id = $attrs.init;
					$scope.price = [];
					$scope.sizeArr = [];

					$scope.$parent.goodsArr.push($scope);

					var bool = false, price = $attrs.price.split('|');

					for(var i=0;i<price.length;i++) {
						$scope.price.push([parseInt(price[i].split(',')[0]),parseInt(price[i].split(',')[1])]);
					}

					$scope.cboxAct = function() {//子级checkbox控制

						bool = false;
						for(var i=0;i<$scope.sizeArr.length;i++) {
							
							if(!$scope.sizeArr[i].cbox) {
								bool = true;
								break;
							}
						}

						if(bool)
							$scope.cbox = false;
						else
							$scope.cbox = true;
						$scope.cPrice();
					}

					$scope.boxClick = function(opt) {

						$scope.cbox = opt != undefined ? opt : !$scope.cbox;
						if($scope.cbox)
							for(var i=0;i<$scope.sizeArr.length;i++) {
								$scope.sizeArr[i].cbox = true;
							}
						else
							for(var i=0;i<$scope.sizeArr.length;i++) {
								$scope.sizeArr[i].cbox = false;
							}

						$scope.cPrice();
					}

					$scope.del = function() {

						new jBox('Confirm', {
							confirmButton: '确定',
							cancelButton: '取消',
							content: '确定删除该货品?',
							confirm: function() {

								var _items = [];

								for(var i=0;i<$scope.sizeArr.length;i++) {
									_items.push({
										'itemid': $scope.sizeArr[i].itemid,
										'oper': 'delete'
									});
								}
								$http({
									method: 'POST',
									url: '/control/command',
									params: {
										'command': 'com.jackrain.ds.CommESShopCartSave',
										'getjson': true,
										'JSON': JSON.stringify([{
											'ad_client': $scope.$parent.id,
											'goodsid': $scope.id,
											'id': $scope.$parent.shoid,
											'items': _items
										}])
									}
								}).then(function(res) {

									if(res.data.code == 0 && res.data.message == '操作完成') {

										new jBox('Notice', {
										    autoClose: 500,
											addClass: 'font-b',
											content: '删除成功',
											position: {
												x: 'center',
												y: 50
											},
											onClose: function() {
												window.location.reload();
											}
										});	
									} else
										new jBox('Notice', {
										    autoClose: 500,
											addClass: 'font-b',
											content: '删除失败,请稍候重试',
											position: {
												x: 'center',
												y: 50
											}
										});
										
								});
							}
						}).open();
					}

					$scope.$watch('cbox', function(val) {

						if(val)
							$scope.$parent.cboxAct();
						else
							$scope.$parent.cbox = false;

						$scope.$parent.$parent.allCount();
					});

					$scope.cPrice = function() {
						
						if($scope.ismix == 'Y') {
							var num = 0;
							for(var i=0;i<$scope.sizeArr.length;i++) {
								
								if($scope.sizeArr[i].cbox) {
									num += parseInt($scope.sizeArr[i].num);
								}
							}
							var price = $scope.price[2] && num > $scope.price[2][0] ?//大于第三个价格段
												$scope.price[2][1] : $scope.price[1] && num > $scope.price[1][0] ?//大于第二个价格段
														$scope.price[1][1] : $scope.price[0][1];
							for(var i=0;i<$scope.sizeArr.length;i++) {
								
								if($scope.sizeArr[i].cbox) {
									$scope.sizeArr[i].price = price;
								} else
									$scope.sizeArr[i].price = $scope.price[2] && $scope.sizeArr[i].num > $scope.price[2][0] ?//大于第三个价格段
																$scope.price[2][1] : $scope.price[1] && $scope.sizeArr[i].num > $scope.price[1][0] ?//大于第二个价格段
																	$scope.price[1][1] : $scope.price[0][1];
							}
						} else
							for(var i=0;i<$scope.sizeArr.length;i++) {
								
								$scope.sizeArr[i].price = $scope.price[2] && $scope.sizeArr[i].num > $scope.price[2][0] ?//大于第三个价格段
																$scope.price[2][1] : $scope.price[1] && $scope.sizeArr[i].num > $scope.price[1][0] ?//大于第二个价格段
																	$scope.price[1][1] : $scope.price[0][1];
							}
					}
				}]
			}
		}])
		.directive('size', ['$http', function($http) {

			return {
				restrict: 'A',
				scope: true,
				controller: ['$scope', '$element', '$attrs', function($scope, $el, $attrs) {
					$scope.cbox = false;
					$scope.num = $attrs.num;
					$scope.itemid = $attrs.itemid;
					$scope.sv = $attrs.specvalue;

					$scope.price = $scope.$parent.price[2] && parseInt($scope.num) > $scope.$parent.price[2][0] ?//大于第三个价格段
											$scope.$parent.price[2][1] : $scope.$parent.price[1] && parseInt($scope.num) > $scope.$parent.price[1][0] ?//大于第二个价格段
													$scope.$parent.price[1][1] : $scope.$parent.price[0][1];

					$scope.$parent.sizeArr.push($scope);
					$scope.$parent.$parent.allSize.push($scope);
					$scope.$parent.$parent.$parent.allSize.push($scope);

					$scope.$watch('num', function(val, old) {

						$scope.num = val.replace(/\D|\s/gi,'') != ''?
									  parseInt(val.replace(/\D|\s/gi,'')) + '' : 1 + '';
					});

					$scope.numChange = function() {
						if(parseInt($scope.num) > 0) {//修改数量

							$http({
								method: 'POST',
								url: '/control/command',
								params: {
									'command': 'com.jackrain.ds.CommESShopCartSave',
									'getjson': true,
									'JSON': JSON.stringify([{
										'ad_client': $scope.$parent.$parent.id,
										'items': [{
											'itemid': $scope.itemid,
											'qty': $scope.num,
									      	'specvalue': $scope.sv,
									      	'spec1': $scope.sv.split('|')[0],
									      	'spec2': $scope.sv.split('|')[1],
									      	'goodsid': $scope.$parent.id,
										}]
									}])
								}
							}).then(function(res) {
								if(res.data.code != 0 || res.data.message != '操作完成') {
									new jBox('Notice', {
										autoClose: 500,
										addClass: 'font-b',
										content: '更新数量失败,请稍候再试',
										position: {
											x: 'center',
											y: 50
										}
									});

								} else {//修改成功更新价格

									var stock = res.data.values[0].items[0]['storage_qty'];

									if(stock > 0 && $scope.num > stock)
										$scope.num = stock + '';

									$scope.cbox = true;
									$scope.$parent.cPrice();
									$scope.$parent.$parent.$parent.allCount();
								}
							}, function(res) {

								if(!res.data) {
									new jBox('Notice', {
										autoClose: 500,
										addClass: 'font-b',
										content: '更新数量失败,请稍候再试',
										position: {
											x: 'center',
											y: 50
										}
									});
								}
							});
						}
					}

					$scope.count = function(opt) {

						$scope.num = opt ? parseInt($scope.num)+1+'' :
										(parseInt($scope.num)-1) > 0 ?
											parseInt($scope.num)-1+'' : '1';
						$scope.numChange();
					}

					$scope.del = function() {

						new jBox('Confirm', {
							confirmButton: '确定',
							cancelButton: '取消',
							content: '确定删除该规格?',
							confirm: function() {
								$http({
									method: 'POST',
									url: '/control/command',
									params: {
										'command': 'com.jackrain.ds.CommESShopCartSave',
										'getjson': true,
										'JSON': JSON.stringify([{
											'ad_client': $scope.$parent.$parent.id,
											'goodsid': $scope.$parent.id,
											'id': $scope.$parent.$parent.shoid,
											'items': [{
												'itemid': $scope.itemid,
										      	'oper': 'delete'
											}]
										}])
									}
								}).then(function(res) {

									if(res.data.code == 0 && res.data.message == '操作完成') {

										new jBox('Notice', {
										    autoClose: 500,
											addClass: 'font-b',
											content: '删除成功',
											position: {
												x: 'center',
												y: 50
											},
											onClose: function() {
												window.location.reload();
											}
										});
									} else
										new jBox('Notice', {
										    autoClose: 500,
											addClass: 'font-b',
											content: '删除失败,请稍候重试',
											position: {
												x: 'center',
												y: 50
											}
										});
										
								});
							}
						}).open();
					}

					$scope.$watch('cbox', function(val) {

						if(val)
							$scope.$parent.cboxAct();
						else
							$scope.$parent.cbox = false;

						$scope.$parent.cPrice();
						$scope.$parent.$parent.$parent.allCount();
					});
				}]
			}
		}]);

		angular.element(document).ready(function() {
			angular.bootstrap(document, ['app']);
		});
		
		return app;
	});
})();